/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CoUpPanel.java
 *
 * Created on 01/12/2011, 01:09:51
 */
package proj5labbd.graphics.comercial;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Painel de atualização dos comerciais da base de dados
 */
public class CoUpPanel extends OperationPanel {

    /** Creates new form CoUpPanel */
    public CoUpPanel(ComercialFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbUpdate.addActionListener(new ComercialAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnInsert1 = new javax.swing.JPanel();
        jlbTitulo1 = new javax.swing.JLabel();
        jtxtTitulo = new javax.swing.JTextField();
        jlbDesc = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtxaDesc = new javax.swing.JTextArea();
        jlbDept1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbDept = new javax.swing.JTable();
        jbUpdate = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtUpdate = new javax.swing.JTable();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Update"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnInsert1.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de inserção"));

        jlbTitulo1.setText("Título");

        jlbDesc.setText("Descrição");

        jtxaDesc.setColumns(20);
        jtxaDesc.setRows(5);
        jScrollPane1.setViewportView(jtxaDesc);

        jlbDept1.setText("Departamento");

        jtbDept.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtbDept);

        javax.swing.GroupLayout jpnInsert1Layout = new javax.swing.GroupLayout(jpnInsert1);
        jpnInsert1.setLayout(jpnInsert1Layout);
        jpnInsert1Layout.setHorizontalGroup(
            jpnInsert1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsert1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsert1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlbTitulo1)
                    .addComponent(jtxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlbDesc)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                    .addComponent(jlbDept1))
                .addContainerGap())
        );
        jpnInsert1Layout.setVerticalGroup(
            jpnInsert1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsert1Layout.createSequentialGroup()
                .addComponent(jlbTitulo1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbDesc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbDept1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(187, 187, 187))
        );

        jbUpdate.setText("Atualizar");

        jtUpdate.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane3.setViewportView(jtUpdate);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE)
                            .addComponent(jpnInsert1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnInsert1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbUpdate))
        );
    }// </editor-fold>//GEN-END:initComponents

    //evento ocasionado pela apresentação do painel ao usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar os dados das tabelas.");
        }
    }//GEN-LAST:event_formComponentShown

    //ação tomada quando há um click de mouse no painel
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtUpdate.clearSelection();
        jtbDept.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jbUpdate;
    private javax.swing.JLabel jlbDept1;
    private javax.swing.JLabel jlbDesc;
    private javax.swing.JLabel jlbTitulo1;
    private javax.swing.JPanel jpnInsert1;
    private javax.swing.JTable jtUpdate;
    private javax.swing.JTable jtbDept;
    private javax.swing.JTextArea jtxaDesc;
    private javax.swing.JTextField jtxtTitulo;
    // End of variables declaration//GEN-END:variables
    //configura a(s) tabela(s) a partir de dados adquiridos da base d dados
    private void setupTable() throws SQLException {
        
        String [] fieldsCo = {"comercial.idPr","comercial.tituloPr","comercial.descricaoPr",
            "comercial.idDe","departamento.nomeDe" };
        String [] titlesCo = {"ID Comercial","Titulo","Descricao","ID Departamento","Nome do departamento"};
        String [] paramsCo = {"comercial.idDe=departamento.idDe"};
        String [][] resultCo = dbInterface.view(fieldsCo,paramsCo,new String[]{"comercial","departamento"});

        DefaultTableModel model = new DefaultTableModel(resultCo,titlesCo);
        jtUpdate.setModel(model);
        
        String[] fields = {"idDe", "nomeDe", "telefoneDe", "nroFuncionariosDe", "cnpjEm"};
        String[][] s = dbInterface.view(fields, null, new String[]{"departamento"});
        DefaultTableModel modelIn = new DefaultTableModel(s, new String[]{"ID", "Nome do departamento","Telefone"
                    ,"Nro de funcionários","Emissora (CNPJ)"});
        jtbDept.setModel(modelIn);
        jtbDept.setRowSelectionAllowed(true);
    }
    
    //ouvinte de evento destiado ao botão de atualização
    class ComercialAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            
            ArrayList<String> fields = new ArrayList<String>();
            
            if (jtxtTitulo.getText().trim().compareTo("") != 0) {
                fields.add("comercial.tituloPr='"+jtxtTitulo.getText()+"'");
            }
            
            if (jtxaDesc.getText().trim().compareTo("") != 0) {
                fields.add("comercial.descricaoPr='"+jtxaDesc.getText()+"'");
            }
            
            if (jtbDept.getSelectedRowCount() == 1) {
                fields.add("comercial.idDe="
                        + jtbDept.getValueAt(jtbDept.getSelectedRow(), 0));
            }
            
            if (fields.size() > 0 && jtUpdate.getSelectedRowCount() > 0) {
                String s;
                String [] params = new String[1];
                String [] fieldsArray = new String[fields.size()];
                fields.toArray(fieldsArray);
                int [] rows = jtUpdate.getSelectedRows();
                for ( int i = 0; i < rows.length; i++ ) {
                    try {
                        params[0] = "comercial.idPr="+jtUpdate.getValueAt(rows[i],0).toString();
                        dbInterface.update(fieldsArray, params,
                                new String[]{"comercial"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Não foi possível "
                                + "atualizar os dados da " + rows[i] + "linha no banco.");
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você deve selecionar os "
                        + "registros a serem modificados e inserir nos campos as modificações");
            }
            
            jtUpdate.clearSelection();
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }
            
        }
    }
}
